package com.gmcas.service;

import com.gmcas.dao.entity.User;
import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.junit.Test;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * Created by zhangshuai on 2017/9/14.
 *  用于对初始密码进行加盐处理、加密以及校验
 */
@Service
public class PasswordHelper {

    // 加密算法是md5
    private String algorithmName = "md5";
    //用于产生随机数的方法,其比UUID要慢很多,安全待待确定
    private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();

    //哈希迭代的次数
    private int hashIterators = 2;

    public void setAlgorithmName(String algorithmName) {
        this.algorithmName = algorithmName;
    }

    public void setRandomNumberGenerator(RandomNumberGenerator randomNumberGenerator) {
        this.randomNumberGenerator = randomNumberGenerator;
    }

    public void setHashIterators(int hashIterators) {
        this.hashIterators = hashIterators;
    }

    public String encryptPassword(User user){
        //获得盐
        String salt = randomNumberGenerator.nextBytes().toHex();
        user.setSalt(salt);
        //由username替换掉salt的前几位,即数据库存储的是假盐,真盐需要特殊处理
//        String userSalt = username + salt.substring(username.length(),salt.length());

        /**
         *  algorithmName 算法名称
         *  password    用户密码
         *  ByteSource.Util.bytes(user.getCredentialsSalt()) 盐
         *  hashIterators 哈希迭代次数
         */
        return new SimpleHash(algorithmName, user.getPassword(),
                ByteSource.Util.bytes(user.getCredentialsSalt()), hashIterators).toString();
    }

    /**
     * 比较SecureRandomNumberGenerator与UUID获得随机数的效率
     *      安全问题,待确定
     */
    @Test
    public void test(){
        long l1 = System.currentTimeMillis();
        String s1 = randomNumberGenerator.nextBytes().toHex();
        long l2 = System.currentTimeMillis();
        System.out.println(l2 - l1);

        long l3 = System.currentTimeMillis();
        String s2 = UUID.randomUUID().toString().replace("-","");
        long l4 = System.currentTimeMillis();
        System.out.println(l4 - l3);
        System.out.println("1:" + s1 + ",2:" + s2);
    }

    //测试采用真假盐的方式的效果
    @Test
    public void test2(){
        String s1 = randomNumberGenerator.nextBytes().toHex();

        String username = "张帅";

        String userSalt = username + s1.substring(username.length(), s1.length());

        System.out.println(s1 + "\t" + username + "\t" + userSalt);
    }
}
